import { AfterViewInit, Component, Input, OnInit, Renderer2 } from '@angular/core';
import { CdkDragDrop, moveItemInArray, transferArrayItem } from '@angular/cdk/drag-drop';
import { ApesMessageService } from '@shared/apes/message';
import { ApiService } from '@core/services/http/api.service';
import { isNotNil } from '@shared/apes/core/util/check';


interface layoutModel {
  class: string,
  layout: string[]
}

interface canvasContent {
  id: string | null,
  applet: any,
  belongColumn: number,
  belongOrder: number,
  canvas: any,
  // className: string,
  customMetadata: string | undefined
}

@Component({
  selector: 'current-panel',
  templateUrl: './currentPanel.component.html',
})

export class CurrentPanelComponent implements OnInit, AfterViewInit {

  addAppletVisible: boolean = false; // 添加小程序弹框
  composeVisible: boolean = false; // 编辑排版弹框

  site: number; //  添加小程序位置

  params: any;

  layoutModel: layoutModel; // 排版模块
  areas = [];  // 所有的区域
  curCanvas: any; // 当前展示看板
  // allCanvas: any = []; // 全部看板
  composeHeight: any; // 看板高度

  @Input() data:any;

  // 预设布局模式
  presetLayoutModel: layoutModel[] = [
    { class: 'layout-a', layout: ['100%'] },
    { class: 'layout-aa', layout: ['50%', '50%'] },
    { class: 'layout-ba', layout: ['30%', '70%'] },
    { class: 'layout-ab', layout: ['70%', '30%'] },
    { class: 'layout-aaa', layout: ['33%', '33%', '33%'] },
  ];

  constructor(private renderer: Renderer2,
              private msg: ApesMessageService,
              private apiService: ApiService) {
  }

  ngOnInit() {
    this.initWidget();
  }

  ngAfterViewInit() {
    this.dynamicHeight();
  }

  // 次级按钮层
  onEvent(data: string) {
    if (data === 'add') {
      this.openAppletAddDialog();
    } else if (data === 'compose') {
      this.openComposeEditDialog();
    }
  }

  // 初始化小程序
  initWidget() {
    this.curCanvas = {};
    this.apiService.post('bi.canvas.findAll', {}).subscribe(body => {
      if (body && isNotNil(body.content) && body.content.length > 0) {
        // console.log(body);
        // this.allCanvas = body.content;
        // console.log(this.data);

        if(JSON.stringify(this.data) == "{}"){
          body.content.forEach((res)=>{
            if(res['defaultFlag']){
              this.curCanvas = res;
            }
          })
        }else{
          if(!this.data['canvasContents']){
            this.data['canvasContents'] = [];
          }
          this.curCanvas = this.data;
        }// 默认展示看板 TODO: 筛选默认看板规则

        // 当前布局模式， 当前的最大列数
        this.layoutModel = this.presetLayoutModel.filter(item => item.class === this.curCanvas.className)[0];
        const columns = this.layoutModel.layout.length;

        for (let i = 0; i < columns; i++) {
          let curArea = [];
          let curAreaIndex = this.areas.length + 1;
          this.curCanvas.canvasContents.forEach(item => {
            if (item.belongColumn === curAreaIndex) curArea.push(item);
          });
          curArea.sort((item1, item2) => item1.belongOrder - item2.belongOrder);  // 排序
          this.areas.push(curArea);
        }
        this.dynamicHeight();
      }
    });
  }

  // 添加小程序
  addWidget() {
    //TODO: 筛选功能  弹窗查询
    this.apiService.post('bi.applet.findAll', {}).subscribe(body => {
      if (body && isNotNil(body.content) && body.content.length > 0) {
        let curArea = this.areas[this.site];
        let tempContent: canvasContent = {
          id: null,
          applet: body.content[0],
          belongColumn: this.site,
          belongOrder: this.areas[this.site].length,
          canvas: { id: this.curCanvas.id },
          customMetadata: null,
        };
        curArea.push(tempContent);
        this.addAppletVisible = false;
        this.dynamicHeight();

        // 保存当前的布局
        // debugger;
        this.curCanvas.canvasContents.push(tempContent);
        this.saveCurPosition(this.areas);
      }
    });
  }

  // 动态拖拽
  drop(event: CdkDragDrop<string[]>) {
    if (event.previousContainer === event.container) {
      moveItemInArray(event.container.data, event.previousIndex, event.currentIndex);
    } else {
      transferArrayItem(event.previousContainer.data,
        event.container.data,
        event.previousIndex,
        event.currentIndex);
    }
    this.dynamicHeight();
    this.saveCurPosition(this.areas);
  }

  // 获取动态高度
  dynamicHeight() {
    setTimeout(() => {
      if (!this.composeHeight) {
        let composeContainer = document.querySelector('.dashboard-group');
        this.composeHeight = composeContainer.clientHeight - (16 + 16);
      }
      let composeList = document.querySelectorAll('.currentPanel-list');
      for (let a = 0; a < composeList.length; a++) {
        this.renderer.removeStyle(composeList[a], 'minHeight');
      }
      let composeHeight = this.composeHeight;
      for (let i = 0; i < composeList.length; i++) {
        if (composeList[i].clientHeight > composeHeight) {
          composeHeight = composeList[i].clientHeight;
        }
      }
      for (let i = 0; i < composeList.length; i++) {
        this.renderer.setStyle(composeList[i], 'minHeight', composeHeight + 'px');
      }
    }, 100);
  }

  // 保存当前位置到服务端
  saveCurPosition(e) {
    let curPostion = [];
    e.forEach((columnItem, columnIndex) => {
      columnItem.forEach((lineItem, lineIndex) => {
        lineItem.belongColumn = columnIndex + 1; // 表内部的排序从 1开始
        lineItem.belongOrder = lineIndex + 1;
        lineItem.className = this.layoutModel.class;
        curPostion.push(lineItem);
      });
    });
    this.curCanvas.canvasContents = curPostion;
    this.apiService.post('bi.canvas.update', this.curCanvas).subscribe(body => {
      if (body) this.curCanvas = body; // 设置为最新的数据，乐观锁
    });
  }


  // 排版弹框
  openComposeEditDialog() {
    this.composeVisible = true;
    let composeList = document.querySelectorAll('.modal-compose-content');
    this.presetLayoutModel.forEach((value, index) => {
      this.renderer.removeClass(composeList[index], 'active');
      if (value.class == this.layoutModel.class) {
        this.renderer.addClass(composeList[index], 'active');
      }
    });
  }

  // 编辑排版
  editLayout(index) {
    let preLayoutModel: layoutModel = this.layoutModel;
    let curLayoutModel: layoutModel = this.presetLayoutModel[index];

    this.layoutModel = curLayoutModel;

    // 分两种情况 1. 少变多(补齐) 2. 多变少 (移到上一个节点)
    if (curLayoutModel.layout.length > preLayoutModel.layout.length) {
      for (let i = this.areas.length, len = curLayoutModel.layout.length; i < len; i++) {
        this.areas.push([]);
      }
    } else {
      for (let i = this.areas.length, len = curLayoutModel.layout.length; i > len; i--) {
        this.areas[i - 2] = [...this.areas[i - 2], ... this.areas[i - 1]]; // 合并倒数第二项和倒数第一项
        this.areas.pop(); // 删除最末尾的值
      }
    }

    // 关闭弹窗，重新渲染
    this.composeVisible = false;
    this.dynamicHeight();
    this.saveCurPosition(this.areas);
  }

  //小程序弹框打开与关闭
  openAppletAddDialog(index = 0) {
    this.site = index;
    this.addAppletVisible = true;
  }

  // 关闭弹框
  closeCanvasDialog() {
    this.addAppletVisible = false;
    this.composeVisible = false;
  }

  moreTool() {
    this.msg.error('功能暂未开放');
  }

  // 小程序搜索
  appletSearch() {
    this.msg.error('功能暂未开放');
  }
}
